/**
 * Copyright (c) 2016-2019 优博信息科技 All rights reserved.
 *
 * https://www.jnyoubo.com
 *
 * 版权所有，侵权必究！
 */

package com.youbo.interceptor;


import com.youbo.annotation.Login;
import com.youbo.common.exception.RRException;
import com.youbo.common.utils.RedisUtils;
import com.youbo.entity.TokenEntity;
import com.youbo.service.TokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 权限(Token)验证
 *
 * @author macy
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisUtils redisUtils;


    public static final String USER_KEY = "userId";
    public static final String TOKEN_TYPE = "tokenType";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        String tokenType = request.getHeader("tokenType");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isBlank(tokenType)){
            tokenType = request.getParameter("tokenType");
        }

        //token为空
        if(StringUtils.isBlank(token)){
            throw new RRException("token不能为空");
        }
        if(StringUtils.isBlank(tokenType)){
            tokenType="0";
        }





        //查询token信息
        TokenEntity tokenEntity =tokenService.queryByToken(token,Integer.valueOf(tokenType));

        if(tokenEntity == null){
            throw new RRException("token 无效",HttpStatus.UNAUTHORIZED.value());
        }

        if(new Date().after(tokenEntity.getExpireTime())){
            throw new RRException("token失效，请重新登录",HttpStatus.UNAUTHORIZED.value());
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, tokenEntity.getUserId());
        request.setAttribute(TOKEN_TYPE, tokenEntity.getTokenType());
        return true;
    }
}
